package com.hmall.common.config.rabbitmq;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class MqConsumeErrorAutoConfiguration {

    final private String exchangeName = "error.direct";


    @Value("${spring.application.name}")
    private String serviceName;

    // 使用编译时常量 + 运行时拼接，但通过@Value注入保证可用性
    @Value("#{T(java.lang.String).format('%s.error.queue', environment.getProperty(\"spring.application.name\"))}")
    private String queueName;


    @Bean
    public DirectExchange directExchange(){
        return ExchangeBuilder.directExchange(exchangeName).delayed().build();
    }


    @Bean
    public Queue errorQueue(){
        return QueueBuilder.durable(queueName).build();
    }

    @Bean
    public Binding errorBinding(){
        return BindingBuilder.bind(errorQueue())
                .to(directExchange()).with(serviceName);
    }

    @Bean
    //如果配置中开启消费者失败重试机制 加载这个bean
    @ConditionalOnProperty(name = "spring.rabbitmq.listener.simple.retry.enabled", havingValue = "true")
    public RepublishMessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate, exchangeName, serviceName);
    }

//    @RabbitListener(queues = "${spring.application.name}.error.queue")
//    public void handleErrorMessage(Message message) {
//        log.error("收到消费失败的消息，准备后续处理：{}", message);
//        // 可以写入日志系统、数据库、发邮件等
//    }

}
